class UpdateOrganization < Mutations::Command
  include Wisper::Publisher

  required do
    model  :organization
    string :name
    string :rank
    string :category
  end

  optional do
    integer :parent_id
    array   :requre_certificate_organs
  end

  def execute
    unless organization_rank = Organization::Rank.find_by_name(rank)
      add_error(:rank, :organization_rank_not_exist, '机构等级不存在')
      return
    end

    unless organization_category = Organization::Category.find_by_name(category)
      add_error(:category, :organization_category_not_exist, '机构类型不存在')
      return
    end

    organization.parent_id = parent_id
    organization.rank      = organization_rank
    organization.category  = organization_category
    organization.name      = name
    if organization.save
      unless requre_certificate_organs.empty?
        AssignmentPositionStandard.run(organization_id: organization.id, requre_certificate_organs: requre_certificate_organs)
      end
      return organization
    else
      organization.errors.each do |key, value|
        add_error(key, key, value)
      end
    end

  end
end